package com.ljb.android.comm.router.core

import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import com.google.gson.JsonObject
import com.ljb.android.comm.common.CommConstant
import com.ljb.android.comm.router.CommRouter
import com.ljb.android.comm.utils.UrlUtils
import com.ljb.android.comm.utils.XLog
import net.ljb.kt.utils.JsonParser
import java.net.URLDecoder

class SchemeHelper {

    /**
     * 创建Scheme路由
     * */
    fun createSchemeUrl(routerAction: RouterAction): String {
        var result = ""
        try {
            result = StringBuilder(CommRouter.Scheme.run { "$SCHEME$HOST$PATH" })
                .append("?")
                .append(CommRouter.Scheme.ACTION)
                .append("=")
                .append(JsonParser.toJson(routerAction))
                .toString()
            XLog.i("createUrl:: $result")
        } catch (e: Exception) {
            XLog.e(e)
        }

        return result
    }

    // actionType : call 路由容器
    private val mRouterCallGroup =
        HashMap<String, IRouterCall?>()

    /**
     * Scheme 路由跳转
     * */
    fun jumpUrl(
        context: Context,
        jumpUrl: String?,
        callBefore: ((context: Context, action: RouterAction) -> Unit)? = null,
        callAfter: ((context: Context, json: String?) -> Unit)? = null
    ) {
        try {
            XLog.i("jumpUrl:: $jumpUrl")
            //校验协议
            if (TextUtils.isEmpty(jumpUrl)) return
            val schemeUrl = CommRouter.Scheme.run { "$SCHEME$HOST$PATH" }
            if (jumpUrl!!.startsWith(schemeUrl)) {
                var actionJson = UrlUtils.getUrlParam(jumpUrl, CommRouter.Scheme.ACTION)
                actionJson = URLDecoder.decode(actionJson)
                val routerAction = JsonParser.fromJsonObj(actionJson, RouterAction::class.java)
                dispatchAction(context, routerAction, callBefore, callAfter)
            }
        } catch (e: Exception) {
            XLog.e(e)
        }
    }

    /**
     * 根据action_type分发路由
     * */
    private fun dispatchAction(
        context: Context,
        routerAction: RouterAction,
        callBefore: ((context: Context, action: RouterAction) -> Unit)? = null,
        callAfter: ((context: Context, json: String?) -> Unit)? = null
    ) {
        if (TextUtils.isEmpty(routerAction.action_type)) return


        when (routerAction.action_type) {
            CommRouter.Scheme.ACTION_TYPE_JUMP -> {
                // 跳转页面
                jumpAction(context, routerAction, callBefore, callAfter)
            }
            CommRouter.Scheme.ACTION_TYPE_CALL -> {
                // 调用功能
                callAction(context, routerAction, callBefore, callAfter)
            }
            else -> {
                XLog.e("未知行为类型（action_type）：：${routerAction.action_type}")
            }
        }
    }

    /**
     * 调起功能
     * */
    private fun callAction(
        context: Context,
        routerAction: RouterAction,
        callBefore: ((context: Context, action: RouterAction) -> Unit)? = null,
        callAfter: ((context: Context, json: String?) -> Unit)? = null
    ) {
        if (TextUtils.isEmpty(routerAction.path)) return


        // 为了拦截器方便处理路由 , 所有的路由跳转都会携带自身对应的Scheme路由
        val bundle = getParams(routerAction.params)
        bundle.putString(CommConstant.Key.KEY_JUMP_URL, createSchemeUrl(routerAction))

        // 通过优先级，开始触发拦截器
        val keys = RouterManager.getIntercepts().mInterceptorsPriority.keys
        if (keys.isNotEmpty()) {
            keys.forEach {
                val interceptor = RouterManager.getIntercepts().mInterceptorsPriority[it]
                val isIntercept = interceptor?.onIntercept(
                    context,
                    routerAction.path!!,
                    bundle
                )
                if (isIntercept != null && isIntercept) {
                    XLog.w("${interceptor::class.java.simpleName} 拦截了路由：${routerAction.path}")
                    return@callAction
                }
            }
        }

        // 正常触发 call
        callBefore?.invoke(context, routerAction)
        var resultJson: String? = null
        val call = mRouterCallGroup[routerAction.path]
        if (call != null) {
            // 自定义的Call功能实现
            resultJson = call.handleCall(context, routerAction.path!! , bundle)
        } else {
            when (routerAction.page_type) {
                CommRouter.Scheme.PAGE_TYPE_NATIVE,
                CommRouter.Scheme.PAGE_TYPE_WEB,
                CommRouter.Scheme.PAGE_TYPE_RN -> {
                    // TODO 公共的Call功能实现
                }
            }
        }
        callAfter?.invoke(context, resultJson)
    }

    /**
     * 跳转页面
     * */
    private fun jumpAction(
        context: Context,
        routerAction: RouterAction,
        callBefore: ((context: Context, action: RouterAction) -> Unit)? = null,
        callAfter: ((context: Context, json: String) -> Unit)? = null
    ) {
        if (TextUtils.isEmpty(routerAction.page_type) || TextUtils.isEmpty(routerAction.path)) return

        callBefore?.invoke(context, routerAction)

        // 为了拦截器方便处理路由 , 所有的路由跳转都会携带自身对应的Scheme路由
        val bundle = getParams(routerAction.params)
        bundle.putString(CommConstant.Key.KEY_JUMP_URL, createSchemeUrl(routerAction))

        when (routerAction.page_type) {
            CommRouter.Scheme.PAGE_TYPE_NATIVE,
            CommRouter.Scheme.PAGE_TYPE_WEB -> {
                // 原生页面 & H5 处理方式一样
                RouterManager.goActivity(
                    context,
                    routerAction.path!!,
                    bundle
                )
            }
            CommRouter.Scheme.PAGE_TYPE_RN -> {
                // RN

            }
            else -> {
                XLog.e("未知页面类型（page_type）：：${routerAction.page_type}")
            }
        }

        callAfter?.invoke(context, "")
    }


    private fun getParams(params: JsonObject?): Bundle {
        val bundle = Bundle()
        params?.run {
            val keySet = this.keySet()
            keySet.forEach {
                bundle.putString(it, this.get(it).asString)
            }
        }
        return bundle
    }


    fun registerCall(path: String, handler: IRouterCall) {
        mRouterCallGroup[path] = handler
    }

    /*
    // host  ： 项目
    // path1 ： 项目
    // path2 :  入口
    // action : 路由协议
    ercar://com.wuba.ercar/openApp?action="{
        "action_type" : "jump / call",            // 动作类型  跳转 或 功能
        "page_type" : "native / web",             // 跳转的页面类型
        "path" :  "/search/SearchActivity",       // 开发中的实际路由
        "params" : "{ "key" : "kotlin" }"         // 页面参数 或 功能参数
     }"

    wandroid://com.ljb.android.component/openApp?action={
         "action_type":"jump" ,                 // 动作类型  跳转(jump) 或 功能(call)
         "page_type":"native" ,                 // 跳转的页面类型  native  web  RN
         "path":"/search/SearchActivity" ,      // 实际路由地址
         "params":"{ \"key\" : \"kotlin\" }"    // 携带参数
     }

*/

}